/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii
   @Language: C++
   @Datetime: 19-08-23 15:15
   */

class Solution {
public:
	int maxProfit(vector<int>& prices) {
		int i=0, p=0, n=prices.size();
		if(n<2) return 0;
		vector<int> left(n,0), right(n,0);
		for(i=1, p=prices[0]; i<n; ++i){
			p=min(p,prices[i]);
			left[i]=max(left[i-1],prices[i]-p);
		}
		for(i=n-1, p=prices.back(); i--;){
			p=max(p,prices[i]);
			right[i]=max(right[i+1],p-prices[i]);
		}
		for(i=0, p=0; i<n; ++i)
			p=max(p,left[i]+right[i]);
		return p;
	}
};
